package com.example.smartgreenhouse.controller;

import com.example.smartgreenhouse.annotation.JwtToken;
import com.example.smartgreenhouse.annotation.Limit;
import com.example.smartgreenhouse.dto.UserStatsDTO;
import com.example.smartgreenhouse.entity.PasswordUpdateRequest;
import com.example.smartgreenhouse.entity.User;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.service.UserService;
import com.example.smartgreenhouse.utils.JwtUtil;
import com.example.smartgreenhouse.utils.ResponseWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("gsas/api/v1/auth")
public class AuthController {

    private final UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    public AuthController(UserService userService ) {
        this.userService = userService;
    }

    @PostMapping("/register")
    @Limit(
            key = "register",                          // 限流标识（通常作为Key）
            permitsPerSecond = 1.0 ,         // 每秒许可数
            timeout = 500,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "注册过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> register(@RequestBody User user) {
        try {
            User register = userService.register(user);
            return ResponseEntity.ok(ResponseWrapper.success("注册成功", register.getId()));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @PostMapping("/login")
    @Limit(
            key = "login",                          // 限流标识（通常作为Key）
            permitsPerSecond = 1.0 ,         // 每秒许可数
            timeout = 500,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "登录过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> login(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        try {
        User loggedInUser = userService.login(user.getUsername(), user.getPassword());
        //生成JwtToken
        String userId = loggedInUser.getId().toString();
        String role = loggedInUser.getRole();
        String token = jwtUtil.sign(userId, role);
        response.put("user", loggedInUser);
        response.put("token", token);
        return ResponseEntity.ok(ResponseWrapper.success("登陆成功", response));
         } catch (BusinessException e) {
        return ResponseEntity.badRequest()
                .body(ResponseWrapper.badRequest(e.getMessage()));
         }
    }

    @JwtToken
    @PostMapping("/update-password")
    @Limit(
            key = "updatePassword",                          // 限流标识（通常作为Key）
            permitsPerSecond = 1.0 ,         // 每秒许可数
            timeout = 500,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> updatePassword(@RequestBody PasswordUpdateRequest request) {
        try{
            boolean success = userService.updatePassword(request.getUsername(), request.getOldPassword(), request.getNewPassword());
            return ResponseEntity.ok(ResponseWrapper.success("密码修改成功", request.getUsername()));
        }catch (BusinessException e) {
        return ResponseEntity.badRequest()
                .body(ResponseWrapper.badRequest(e.getMessage()));
    }
    }

    @JwtToken
    @GetMapping("/stats")
    @Limit(
            key = "stats",                          // 限流标识（通常作为Key）
            permitsPerSecond = 1.0,                 // 每秒许可数
            timeout = 500,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> getStats(@RequestParam("username") String username) {
        try {
            UserStatsDTO stats = userService.getUserStatistics(username);
            return ResponseEntity.ok(ResponseWrapper.success("统计获取成功", stats));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

}